package com.hdax.dm.pay.controller;

import com.hdax.dm.pay.service.PayService;
import com.hdax.dm.pay.vo.TradeInfoVo;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Map;

@RestController
@RequestMapping(path = "/pay")
public class PayController {

    @Autowired
    private PayService payService;

    /**
     * 支付宝支付订单
     */
    @PostMapping(path = "zhi")
    public void aliPay(HttpServletResponse response, @RequestBody Map<String, String> params) throws Exception{
        response.setContentType("text/html;charset=UTF-8");
        String orderNo = params.get("orderNo");
        PrintWriter out = response.getWriter();
        out.print(payService.aliPay(orderNo));
    }

    @SneakyThrows
    @PostMapping(path = "notify/payed")
    public void payed1(HttpServletRequest request){
        System.out.println("支付宝订单号："+request.getParameter("trade_no"));
        System.out.println("商家订单号："+request.getParameter("out_trade_no"));
        System.out.println("买家支付宝id："+request.getParameter("buyer_id"));
        System.out.println("交易状态："+request.getParameter("trade_status"));
        System.out.println("实收金额："+request.getParameter("receipt_amount"));
        System.out.println("用户支付金额："+request.getParameter("buyer_pay_amount"));
        System.out.println("交易付款时间："+request.getParameter("gmt_payment"));
        TradeInfoVo vo = new TradeInfoVo();
        vo.setTradeNo(request.getParameter("trade_no"));
        vo.setOrderNo(request.getParameter("out_trade_no"));
        vo.setBuyerAccount(request.getParameter("buyer_id"));
        vo.setTradeStatus(request.getParameter("trade_status"));
        vo.setReceiptAmount(Double.parseDouble(request.getParameter("receipt_amount")));
        vo.setBuyerPayAmount(Double.parseDouble(request.getParameter("buyer_pay_amount")));
        vo.setGmtPayment(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(request.getParameter("gmt_payment")));
        payService.payed(vo);
    }

    @PostMapping(path = "return/payed")
    public void payed2(HttpServletRequest request){
        System.out.println("");
    }


    /**
     * 退款
     * @param params
     * @return
     */
    @ResponseBody
    @RequestMapping(path = "/p/refundOrder")
    public String tuikuan(@RequestBody Map<String, String> params){
        String orderno = params.get("orderNo");
        //实现退款功能
        payService.tuikuan(orderno);
        return null;
    }
}
